/*
 * Serve content over a socket
 */
 var rest = require('./rest');
 const checkInterval = 2000
 module.exports = function(io) {
 	var statsData;
 	io.on('connection', function(socket) {
 		rest.logger.info('a user connected');
 		socket.on('disconnect', function(){
 			rest.logger.info('a user disconnected');
 		});
 		if (rest.loaded()) {
			rest.logger.debug("****** socket io: update ******")
			rest.logger.debug(rest.ledgerData());
 			socket.emit('update', JSON.stringify(rest.ledgerData()))
 		}
 		if (statsData) {
			 rest.logger.debug("****** socket io: stat ******")
			 rest.logger.debug(statsData);
 			socket.emit('stats',JSON.stringify(statsData));
 		}
 	});
 	rest.update(function(updated, data) {
 		console.log(data);
 		io.emit('update', JSON.stringify(data));
 		statsData = getStatData(data);
 		console.log(statsData);
 		io.emit('stats',JSON.stringify(statsData));
 	});
 	setInterval(function() {
 		if (!rest.loaded()) return;
 		console.log('peoridically check');
 		rest.update(function(updated, data) {
 			if (updated) {
 				io.emit('update', JSON.stringify(data));
 				statsData = getStatData(data);
 				io.emit('stats',JSON.stringify(statsData));
 			}
 		});
       }, checkInterval);
 }

 var getStatData= function getStatData(ledgerData) {
 	var endSecs = -1;
 	var txnRate = 0;
 	var blkRate = 0;
 	var blkCount = 0;
 	var txnCount = 0;
 	var txnLatency = 0;
 	var currTime;
 	var blkTxGraph = {
 		block : [],
 		txs: []
 	}
 	var txRateGraph = {"time":[],"txRate":[]}
 	var blkRateGraph = {"time":[],"blkRate":[]}
 	var statsData = {
 		"checkTime" : "",
 		"avgTxnLatency" : "",
 		"txnRate": "",
 		"mineRate": "",
 		"txRateGraph":txRateGraph,
 		"blkRateGraph":blkRateGraph
 	};

	// monitor for 10 seconds
	let monitorWindow = 10
 	for (var i = ledgerData.chain.height - 1; i > 0; i--) {
		if(txRateGraph.time.length == 20)
			break;
		var block = ledgerData.blocks[i];
		if (!block || !block.transactions)
			continue;

		if (blkTxGraph.block.length < 20) {
			blkTxGraph.block.push(i);
			blkTxGraph.txs.push(block.transactions.length);
		}
		if (endSecs < 0) {
			currTime = new Date(block.timestamp);
			endSecs = currTime.getTime()/1000;
			currTime = currTime.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
		}
		blockSec = new Date(block.timestamp).getTime()/1000;
		if (blockSec >= (endSecs - monitorWindow)) {
			blkCount++;
			for (var k = 0; k < block.transactions.length; k++) {
				txnCount++;
				txnLatency += (blockSec - new Date(block.transactions[k].timestamp).getTime()/1000);
			}
		} 
		else {
			//console.log("new row " , txRateGraph.time.length);
			txnRate = Math.round(txnCounte/monitorWindow);
			blkRate = Math.round(blkCount/monitorWindow);
		
			statsData = {
				"checkTime" : currTime,
				"avgTxnLatency" : Math.round((txnLatency/txnCount)*1000),
				"txnRate": txnRate,
				"mineRate": blkRate
			}
		
			txRateGraph.time.push(currTime);
			txRateGraph.txRate.push(txnRate);
			blkRateGraph.time.push(currTime);
			blkRateGraph.blkRate.push(blkRate);
		
			endSecs = -1;
			txnRate = 0;
			blkRate = 0;
			txnCount = 0;
			txnLatency = 0;
		}
	}

	statsData = {
		"checkTime" : statsData.checkTime,
		"avgTxnLatency" : statsData.avgTxnLatency,
		"txnRate": statsData.txnRate,
		"mineRate": statsData.mineRate,
		"txRateGraph":txRateGraph,
		"blkRateGraph":blkRateGraph
	}

	statsData.txRateGraph = { "time" : txRateGraph.time.reverse() , "txRate" :txRateGraph.txRate.reverse() };
	statsData.blkRateGraph = { "time" : blkRateGraph.time.reverse() , "blkRate" : blkRateGraph.blkRate.reverse() };
	statsData.blkTxGraph = { "block" : blkTxGraph.block.reverse() , "txs" : blkTxGraph.txs.reverse() };
	//simulated values for now. Will be fixed soon.
	var x = Math.floor(Math.random() * 95) + 76,y=Math.floor(Math.random() * 106) + 91,z=Math.floor(Math.random() * 64) + 37
	statsData.chTx = { "chainCodes" : ["ch01","ch02","ch03"] , "counts": [x,y,z] };
	var x= Math.floor(Math.random() * 834) + 631,y=Math.floor(Math.random() * 232) + 46,z=Math.floor(Math.random() * 56) + 32
	statsData.apprTx = { "stats" : ["Approved","Pending","Rejected"] , "counts": [x,y,z] };

	console.log(' statsData ',statsData);
	return statsData;
}